var express = require('express');
var app = express();
var bodyParser = require('body-parser')
var inputData = require('./libs/TInputData')

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

var inputObj = new inputData.TInputDatas();

app.all('/gk/real', function(req, response) {
    try {
        inputObj.getRealDatas().then(res => {
            response.send(JSON.stringify(res));
        })
    } catch (er) {
        console.log(er);
    }
})
app.all('/gk/day', function(req, response) {
    try {
        try {
            var mn = req.query.mn;
            var start = req.query.start;
            var end = req.query.end;
            var sql = "select mn, time , " +
                " so2, no2 , co , o38 as o3 , pm10 , pm25 , tsp , ta , ua , wd , ws  ," +
                " so2_iqi, no2_iqi , co_iqi , o3_iqi  , pm10_iqi , pm25_iqi  " +
                " from T_D where mn='{mn}' and time>='{start}' and time<'{end}'  tz('Asia/Shanghai')";
            inputObj.getQueryResult(sql, { mn: mn, start: start, end: end }).then(res => {
                res.forEach(r => {
                    r.aqi = inputObj.getAqi(r)
                })
                response.send(JSON.stringify(res));
            })

        } catch (eer) {
            console.log(eer);
        }

    } catch (er) {
        console.log(er);
    }
})
app.all('/gk/hour', function(req, response) {
    try {
        var mn = req.query.mn;
        var start = req.query.start;
        var end = req.query.end;
        var sql = "select mn, time , " +
            " so2, no2 , co , o38 as o3 , pm10 , pm25 , tsp , ta , ua , wd , ws  ," +
            " so2_iqi, no2_iqi , co_iqi , o3_iqi  " +
            " from T_H where mn='{mn}' and time>='{start}' and time<'{end}'  tz('Asia/Shanghai')";
        inputObj.getQueryResult(sql, { mn: mn, start: start, end: end }).then(res => {
            res.forEach(r => {
                r.aqi = inputObj.getAqi(r)
            })
            response.send(JSON.stringify(res));
        })

    } catch (er) {
        console.log(er);
    }
})
app.all('/gk/evaluate', function(req, response) {
    try {
        var start = req.query.start;
        var end = req.query.end;
        inputObj.getMaxI(start, end).then(res => {
            response.send(JSON.stringify(res));
        })

    } catch (er) {
        console.log(er);
    }
})

var server = app.listen(20032, function() {
    var host = server.address().address
    var port = server.address().port

    console.log("应用实例，访问地址为 http://%s:%s", host, port)

})